// --- 认证检查 ---
// 这段代码必须在所有其他逻辑之前执行！
(function() {
    const isLoggedIn = sessionStorage.getItem('isLoggedIn');
    if (isLoggedIn !== 'true') {
        // 如果未登录，重定向到登录页
        // 将当前页面地址作为参数传过去，以便登录后可以跳回来
        window.location.href = `login.html`;
    }
})();

// 使用 DOMContentLoaded 事件确保在操作DOM之前，HTML已完全加载和解析
document.addEventListener('DOMContentLoaded', () => {

    // --- 全局变量 ---
    let sseConnection = null;

    // --- 元素选择 ---
    const menu = document.querySelector('.menu');
    const pageContentContainer = document.getElementById('page-content');
    const firmwareVersionSpan = document.getElementById('firmware-version');
    const headerMessageDiv = document.getElementById('header-message');
    const deviceHostnameSpan = document.getElementById('device-hostname');
    const notificationCenter = document.getElementById('notification-center');
    const notificationBadge = document.getElementById('notification-badge');
    const notificationList = document.getElementById('notification-list');
    const logoutBtn = document.getElementById('logout-btn');

    // 模拟通知数据
    let notifications = [];

    // --- UI 更新函数 ---

    /**
     * 格式化秒数为 d h m s 格式
     * @param {number} totalSeconds
     */
    const formatUptime = (totalSeconds) => {
        const days = Math.floor(totalSeconds / 86400);
        totalSeconds %= 86400;
        const hours = Math.floor(totalSeconds / 3600);
        totalSeconds %= 3600;
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        return `${days}d ${hours}h ${minutes}m ${seconds}s`;
    };

    /**
     * 格式化Unix时间戳为本地时间字符串
     * @param {number} timestamp - Unix时间戳 (秒)
     */
    const formatDeviceTime = (timestamp) => {
        if (!timestamp) return 'N/A';
        const date = new Date(timestamp * 1000);
        return date.toLocaleString('zh-CN');
    };

    /**
     * 加载和初始化状态页面页面
     */
    const initializeStatusPage = async () => {
        try {
            // TODO
        } catch (error) {
            console.error("Failed to initialize status page:", error);
        }
    };

    /**
     * 加载和初始化控制页面
     */
    const initializeControlPage = async () => {
        try {
            const response = await fetch(`/api/status/realtime`);
            const data = await response.json();

            // 更新继电器开关状态和文本
            const relayToggle = document.getElementById('relay-toggle');
            if (relayToggle) {
                const relayStatusText = document.getElementById('relay-status-text');
                relayToggle.checked = data.relay_state;
                relayStatusText.textContent = `当前状态: ${data.relay_state ? '已打开' : '已关闭'}`;
            }

            // 更新RS485波特率选择
            // --- RS485波特率的初始化逻辑 ---
            const baudrateSelect = document.getElementById('rs485-baudrate-select');
            if (baudrateSelect) {
                const customBaudrateInput = document.getElementById('rs485-baudrate-custom');
                const currentBaudrate = data.rs485_baudrate.toString();

                let isCustom = true;
                // 检查当前波特率是否存在于预设选项中
                for (let option of baudrateSelect.options) {
                    if (option.value === currentBaudrate) {
                        baudrateSelect.value = currentBaudrate;
                        isCustom = false;
                        break;
                    }
                }
                
                // 如果是自定义波特率
                if (isCustom) {
                    baudrateSelect.value = 'custom';
                    customBaudrateInput.value = currentBaudrate;
                    customBaudrateInput.style.display = 'block';
                } else {
                    customBaudrateInput.style.display = 'none';
                }
            }

        } catch (error) {
            console.error("Failed to initialize control page:", error);
        }

        // --- 初始化红外遥控部分 (从 initializeIrControlPage 移入) ---
        const coolTempsContainer = document.getElementById('ir-cool-temps');
        if (coolTempsContainer) {
            const heatTempsContainer = document.getElementById('ir-heat-temps');
            const learnCoolTempsContainer = document.getElementById('ir-learn-cool-temps');
            const learnHeatTempsContainer = document.getElementById('ir-learn-heat-temps');

            // 检查元素是否存在，防止在其他页面意外调用时出错
            if (coolTempsContainer && heatTempsContainer) {
                // 清空容器，防止重复生成按钮
                coolTempsContainer.innerHTML = '';
                heatTempsContainer.innerHTML = '';
                learnCoolTempsContainer.innerHTML = '';
                learnHeatTempsContainer.innerHTML = '';
                
                // 动态生成温度按钮 (16-30°C)
                for (let temp = 16; temp <= 30; temp++) {
                    // 控制按钮
                    coolTempsContainer.innerHTML += `<button class="btn" data-command="set_temp" data-mode="cool" data-value="${temp}">${temp}°C</button>`;
                    heatTempsContainer.innerHTML += `<button class="btn" data-command="set_temp" data-mode="heat" data-value="${temp}">${temp}°C</button>`;
                    // 学习按钮
                    learnCoolTempsContainer.innerHTML += `<button class="btn btn-learn" data-command="set_temp" data-mode="cool" data-value="${temp}">学习 ${temp}°C</button>`;
                    learnHeatTempsContainer.innerHTML += `<button class="btn btn-learn" data-command="set_temp" data-mode="heat" data-value="${temp}">学习 ${temp}°C</button>`;
                }
            }
        }
    };

    /**
     * 加载和初始化网络页面
     */
    const initializeNetworkPage = async () => {
        try {
            // TODO
        } catch (error) {
            console.error("Failed to initialize network page:", error);
        }
    };
    
    /**
     * 加载和初始化服务页面
     */
    const initializeServicesPage = async () => {
        try {
            // TODO
        } catch (error) {
            console.error("Failed to initialize services page:", error);
        }
    };

    /**
     * 加载和初始化运维管理页面
     */
    const initializeMaintenancePage = async () => {
        try {
            // 更新固件版本显示
            const fwVersion = document.getElementById('firmware-version').textContent;
            document.getElementById('current-firmware-version').textContent = fwVersion;
        } catch (error) {
            console.error("Failed to initialize maintenance page:", error);
        }
    };

    // --- 函数定义 ---

    /**
     * 统一的、健壮的全局UI更新函数
     * @param {object} data - 从SSE收到的实时数据
     */
    const updateGlobalUI = (data) => {
        // --- 尝试更新所有可能存在的实时元素 ---
        
        // 封装一个安全的更新函数，避免因找不到元素而报错
        const updateElementText = (id, text) => {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = text;
            }
        };

        // 设备状态页的元素
        updateElementText('status-uptime', formatUptime(data.uptime_s));
        updateElementText('status-relay-state', data.relay_state ? '开' : '关');
        updateElementText('status-temp-humidity', `${data.temperature.toFixed(1)}℃ / ${data.humidity.toFixed(1)}%`);
        updateElementText('status-current', `${data.current.toFixed(2)} A`);
        updateElementText('status-voltage', `${data.voltage.toFixed(1)} V`);
        updateElementText('status-power', `${data.power.toFixed(2)} W`);
        updateElementText('status-energy', `${data.energy.toFixed(3)} kWh`);

        // 运维管理页的元素
        // 注意：这里我们同时更新两个页面可能存在的时钟元素
        updateElementText('status-device-time', formatDeviceTime(data.device_time));
        updateElementText('maintenance-device-time', formatDeviceTime(data.device_time));
        
        // 控制页的元素 (例如，如果需要在继电器开关旁边也显示实时状态)
        const relayStatusText = document.getElementById('relay-status-text');
        if (relayStatusText) {
            // 只在用户没有正在操作时更新，避免冲突
            if (!relayStatusText.textContent.includes('切换中')) {
                relayStatusText.textContent = `当前状态: ${data.relay_state ? '已打开' : '已关闭'}`;
            }
        }
    };

    /**
     * 新增函数：启动SSE连接
     */
    const startSseConnection = () => {
        if (sseConnection) return; // 如果已连接，则不重复执行

        console.log("Starting SSE connection...");
        // 创建 EventSource 实例，连接到我们的SSE端点
        sseConnection = new EventSource(`/api/sse`);

        // 监听默认的 'message' 事件
        sseConnection.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                console.log("SSE data received:", data);
                
                // 调用我们已有的UI更新函数
                updateGlobalUI(data);

            } catch (e) {
                console.error("Error parsing SSE data:", e);
            }
        };

        // 监听连接打开事件
        sseConnection.onopen = () => {
            console.log("SSE connection opened.");
            // 可以在这里更新一个UI元素，表示“实时连接中”
            setTimeout(() => {
            addNotification("连接服务器成功");
        }, 2000);
        };

        // 监听错误事件 (例如网络断开)
        sseConnection.onerror = (error) => {
            console.error("EventSource failed:", error);
            // EventSource 会自动尝试重连，我们通常不需要做额外处理
            // sseConnection.close(); // 可以选择在这里关闭，然后稍后手动重试
        };
    };

    /**
     * 新增函数：关闭SSE连接
     */
    const stopSseConnection = () => {
        if (sseConnection) {
            console.log("Closing SSE connection.");
            sseConnection.close();
            sseConnection = null;
        }
    };

    /**
     * 添加一条新通知
     * @param {string} message - 通知内容
     */
    const addNotification = (message) => {
        const now = new Date();
        const timestamp = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
        
        notifications.unshift({ text: `[${timestamp}] ${message}`, read: false });
        
        // 限制通知数量，防止过多
        if (notifications.length > 10) {
            notifications.pop();
        }
        
        updateNotificationUI();
    };

    /**
     * 更新通知中心的UI
     */
    const updateNotificationUI = () => {
        // 更新列表
        notificationList.innerHTML = '';
        if (notifications.length === 0) {
            notificationList.innerHTML = '<div class="notification-item">还没有任何通知</div>';
        } else {
            notifications.forEach(notif => {
                const item = document.createElement('div');
                item.className = `notification-item ${notif.read ? '' : 'unread'}`;
                item.textContent = notif.text;
                notificationList.appendChild(item);
            });
        }

        // 更新角标
        const unreadCount = notifications.filter(n => !n.read).length;
        if (unreadCount > 0) {
            notificationBadge.textContent = unreadCount;
            notificationBadge.style.display = 'block';
        } else {
            notificationBadge.style.display = 'none';
        }
    };

    /**
     * 处理从 URL 升级的函数
     */
    const handleUrlUpgrade = () => {
        const urlInput = document.getElementById('firmware-url');
        const url = urlInput.value.trim();

        if (!url) {
            showHeaderMessage('请输入固件的 URL 地址!', false);
            return;
        }
        // 简单的URL格式验证
        try {
            new URL(url);
        } catch (_) {
            showHeaderMessage('URL 格式不正确!', false);
            return;
        }
        
        if (!confirm(`您确定要从以下地址开始升级吗？\n\n${url}`)) {
            return;
        }

        const progressContainer = document.getElementById('ota-progress-container');
        const progressLabel = document.getElementById('ota-progress-label');
        const progressBar = document.getElementById('ota-progress-bar');
        const progressText = document.getElementById('ota-progress-text');
        const statusMessage = document.getElementById('ota-status-message');
        const upgradeButton = document.getElementById('url-upgrade-btn');

        // 准备升级
        progressContainer.style.display = 'block';
        progressBar.style.width = '0%';
        progressText.textContent = '0%';
        progressLabel.textContent = '下载进度'; // 明确是下载
        statusMessage.textContent = '正在向设备发送升级指令...';
        upgradeButton.disabled = true;

        fetch(`/api/ota/start-url-upgrade`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ url: url }),
        })
        .then(res => {
            if (!res.ok) throw new Error(res.statusText);
            return res.json();
        })
        .then(data => {
            showHeaderMessage(data.message || '升级指令已发送', true);
            statusMessage.textContent = '设备已开始下载固件，请勿断电。您可以通过轮询状态来获取进度。';
            // 在真实场景中，这里会开始轮询升级状态
            // pollOtaStatus();
        })
        .catch(err => {
            statusMessage.textContent = `启动升级失败: ${err.message}`;
            showHeaderMessage(`错误: ${err.message}`, false);
            upgradeButton.disabled = false;
        });
    };

    /**
     * 处理固件上传的函数
     */
    const handleFirmwareUpload = () => {
        const fileInput = document.getElementById('firmware-file');
        const file = fileInput.files[0];
        
        if (!file) {
            showHeaderMessage('请先选择一个固件文件!', false);
            return;
        }

        const progressContainer = document.getElementById('ota-progress-container');
        const progressBar = document.getElementById('ota-progress-bar');
        const progressText = document.getElementById('ota-progress-text');
        const statusMessage = document.getElementById('ota-status-message');
        const uploadButton = document.getElementById('upload-firmware-btn');

        // 准备上传
        progressContainer.style.display = 'block';
        progressBar.style.width = '0%';
        progressText.textContent = '0%';
        statusMessage.textContent = '正在上传固件...';
        uploadButton.disabled = true;

        const formData = new FormData();
        formData.append('firmware', file);

        const xhr = new XMLHttpRequest();
        xhr.open('POST', `/api/ota/upload`, true);

        // 监听上传进度
        xhr.upload.onprogress = (event) => {
            if (event.lengthComputable) {
                const percentComplete = Math.round((event.loaded / event.total) * 100);
                progressBar.style.width = percentComplete + '%';
                progressText.textContent = percentComplete + '%';
            }
        };

        // 监听请求完成
        xhr.onload = () => {
            uploadButton.disabled = false;
            if (xhr.status === 200) {
                statusMessage.textContent = '上传成功！设备正在验证和应用更新，请勿断电...';
                showHeaderMessage('固件上传成功', true);
            } else {
                statusMessage.textContent = `上传失败: ${xhr.responseText}`;
                showHeaderMessage(`错误: ${xhr.status} ${xhr.responseText}`, false);
            }
        };

        // 监听网络错误
        xhr.onerror = () => {
            uploadButton.disabled = false;
            statusMessage.textContent = '上传时发生网络错误。';
            showHeaderMessage('网络错误', false);
        };
        
        xhr.send(formData);
    };

    /**
     * 辅助函数：处理表单提交逻辑
     * @param {string} endpoint - API端点
     * @param {FormData} form - 表单元素
     */
    const handleGenericFormSubmit = async (endpoint, form) => {
        const formData = new FormData(form);
        let data = Object.fromEntries(formData.entries());

        // 手动处理 FormData，以便能正确处理 checkbox
        for (const [key, value] of formData.entries()) {
            if (key === 'enabled') {
                data[key] = true; // 如果 'enabled'存在，则值为 true
            } else {
                data[key] = value;
            }
        }
        // 如果 'enabled' checkbox 未被选中，它不会出现在 FormData 中
        if (!data.hasOwnProperty('enabled')) {
            data.enabled = false;
        }

        // 清理网络配置表单的DHCP数据
        if (endpoint.includes('ethernet') || endpoint.includes('wifi')) {
             const mode = data.eth_mode || data.wifi_mode;
             if (mode === 'dhcp') {
                delete data.ip; delete data.netmask; delete data.gateway; delete data.dns;
             }
        }

        // --- RS485 波特率的特殊处理逻辑 ---
        if (form.id === 'rs485-form') {
            let finalBaudrate;
            if (data.baudrate_select === 'custom') {
                // 如果选择了自定义，使用自定义输入框的值
                finalBaudrate = data.baudrate_custom;
            } else {
                // 否则，使用下拉框的值
                finalBaudrate = data.baudrate_select;
            }
            // 构造最终要提交的数据
            data = { baudrate: finalBaudrate };
        }

        console.log('Submitting to', endpoint, 'with data:', data);

        try {
            const response = await fetch(`${endpoint}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data),
            });

            if (!response.ok) throw new Error(await response.text());
            
            const result = await response.json();
            showHeaderMessage(result.message || 'Settings saved successfully!', true);

        } catch (error) {
            console.error('Failed to submit form:', error);
            showHeaderMessage(`Error: ${error.message}`, false);
        }
    };

    /**
     * 显示顶部消息条
     * @param {string} message - 要显示的消息
     * @param {boolean} isSuccess - true为成功样式, false为错误样式
     */
    const showHeaderMessage = (message, isSuccess = true) => {
        headerMessageDiv.textContent = message;
        headerMessageDiv.className = 'header-message'; // Reset classes
        headerMessageDiv.classList.add(isSuccess ? 'success' : 'error');
        headerMessageDiv.style.opacity = '1';

        setTimeout(() => {
            headerMessageDiv.style.opacity = '0';
        }, 3000); // 3秒后自动隐藏
    };


    /**
     * 动态加载页面内容
     * @param {string} pageName - 页面名称 (例如 'status', 'control')
     */
    const loadPage = async (pageName) => {

        // 显示加载中的提示
        pageContentContainer.innerHTML = '<p>Loading...</p>';

        // 动态加载
        try {
            // 从 /pages/ 目录请求对应的HTML片段
            const response = await fetch(`/pages/${pageName}.html`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            pageContentContainer.innerHTML = await response.text();

            // ---- 页面加载后的特定初始化 ----
            if (pageName === 'status') {
                // 更新状态页数据
                // updateStatusPageUI();
                initializeStatusPage();
            } else if (pageName === 'control') {
                // 如果是控制页，加载其初始状态
                initializeControlPage();
            } else if (pageName === 'network') {
                // 初始化网络数据
                initializeNetworkPage();
            } else if (pageName === 'services') {
                // 初始化服务数据
                initializeServicesPage();
            } else if (pageName === 'maintenance') {
                // 运维页调用新增的初始化函数
                initializeMaintenancePage();
            }

        } catch (error) {
            console.error('Failed to load page:', error);
            pageContentContainer.innerHTML = `<div class="card"><p>Error: Could not load page content. Please check the connection and try again.</p></div>`;
        }
    };

    /**
     * 从ESP32获取固件版本
     */
    const fetchFirmwareVersion = async () => {
        try {
            // 假设ESP32有一个API端点 /api/version 返回JSON
            const response = await fetch('/api/version');
            if (!response.ok) throw new Error('Failed to fetch version');
            
            const data = await response.json(); // e.g. {"version": "1.1.0"}
            firmwareVersionSpan.textContent = `v${data.version}`;

        } catch (error) {
            console.error(error);
            firmwareVersionSpan.textContent = 'N/A';
        }
    };

    // --- 事件监听 ---

    // 点击通知中心铃铛图标
    notificationCenter.addEventListener('click', () => {
        notificationList.classList.toggle('show');
        // 如果打开了列表，将所有通知标记为已读
        if (notificationList.classList.contains('show')) {
            notifications.forEach(n => n.read = true);
            // 稍后更新UI，让角标消失有个延迟效果
            setTimeout(updateNotificationUI, 300);
        }
    });

    // 点击页面其他地方关闭通知列表
    document.addEventListener('click', (event) => {
        if (!notificationCenter.contains(event.target)) {
            notificationList.classList.remove('show');
        }
    });

    // 点击登出按钮
    logoutBtn.addEventListener('click', (event) => {
        event.preventDefault();
        if (confirm('您确定要登出吗？')) {
            // 清除 sessionStorage 中的登录状态
            sessionStorage.removeItem('isLoggedIn');
            sessionStorage.removeItem('username');
            
            // 跳转到登录页
            window.location.href = 'login.html';
        }
    });

    // 使用事件委托来处理菜单点击，更高效
    menu.addEventListener('click', (event) => {
        // 找到被点击的链接元素
        const link = event.target.closest('.menu__link');

        if (link) {
            event.preventDefault(); // 阻止<a>标签的默认跳转行为

            const pageName = link.dataset.page;
            console.log('pageName: ' + pageName)
            if (!pageName) return;

            // 更新菜单的激活状态
            // 1. 移除当前激活项的 'active' 类
            const currentActive = menu.querySelector('.menu__link.active');
            if (currentActive) {
                currentActive.classList.remove('active');
            }
            // 2. 给被点击的项添加 'active' 类
            link.classList.add('active');

            // 加载新页面
            loadPage(pageName);
        }
    });
    
    // 使用事件委托处理动态加载内容中的表单提交
    pageContentContainer.addEventListener('submit', async (event) => {
        event.preventDefault(); // 阻止所有表单的默认提交行为
        const formId = event.target.id;
        let endpoint = null;

        // 根据表单ID确定API端点
        switch(formId) {
            case 'ethernet-form':
                endpoint = '/api/config/ethernet';
                break;
            case 'wifi-form':
                endpoint = '/api/config/wifi';
                break;
            case 'tcp-server-form':
                endpoint = '/api/config/tcp-server';
                break;
            case 'tcp-client-form':
                endpoint = '/api/config/tcp-client';
                break;
            case 'udp-server-form':
                endpoint = '/api/config/udp-server';
                break;
            case 'udp-client-form':
                endpoint = '/api/config/udp-client';
                break;
            case 'change-password-form':
                endpoint = '/api/account/change-password';
                break;
            case 'rs485-form':
                endpoint = '/api/config/rs485';
                break;
        }

        if (endpoint) {
            handleGenericFormSubmit(endpoint, event.target);
        }
    });

    // 使用事件委托来处理动态加载的 radio button 的变化
    pageContentContainer.addEventListener('change', (event) => {
        const target = event.target;
        
        // 确保事件源是我们的模式选择radio button
        if (target.type === 'radio' && (target.name === 'eth_mode' || target.name === 'wifi_mode')) {
            const isStatic = target.value === 'static';
            const prefix = target.name.startsWith('eth') ? 'eth' : 'wifi';
            const staticFieldsContainer = document.getElementById(`${prefix}-static-fields`);

            if (staticFieldsContainer) {
                staticFieldsContainer.style.display = isStatic ? 'block' : 'none';
            }
        }

        // 处理服务配置的启用/禁用开关 ---
        if (target.type === 'checkbox' && target.closest('.service-toggle')) {
            const isEnabled = target.checked;
            const configFields = target.closest('.card').querySelector('.service-config-fields');
            
            if (configFields) {
                if (isEnabled) {
                    configFields.style.display = 'block';
                    // 使用 setTimeout 确保 display:block 生效后再改变 opacity，从而触发过渡效果
                    setTimeout(() => {
                        configFields.style.opacity = '1';
                    }, 10); 
                } else {
                    configFields.style.opacity = '0';
                    setTimeout(() => {
                        configFields.style.display = 'none';
                    }, 400); // 等待过渡动画结束后再隐藏
                }
            }
        }

        // 处理继电器开关
        if (target.id === 'relay-toggle') {
            const state = target.checked;
            const relayStatusText = document.getElementById('relay-status-text');
            relayStatusText.textContent = `正在切换...`;

            fetch(`/api/control/relay`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ state: state }),
            })
            .then(res => res.json())
            .then(data => {
                showHeaderMessage(data.message, true);
                relayStatusText.textContent = `当前状态: ${data.relay_state ? '已打开' : '已关闭'}`;
            })
            .catch(err => {
                showHeaderMessage(`错误: ${err.message}`, false);
                // 切换失败，恢复开关到之前的状态
                target.checked = !state; 
                relayStatusText.textContent = `当前状态: ${!state ? '已打开' : '已关闭'}`;
            });
        }

        // 处理波特率下拉框变化
        if (target.id === 'rs485-baudrate-select') {
            const customBaudrateInput = document.getElementById('rs485-baudrate-custom');
            if (target.value === 'custom') {
                customBaudrateInput.style.display = 'block';
                customBaudrateInput.focus(); // 自动聚焦，方便用户输入
            } else {
                customBaudrateInput.style.display = 'none';
            }
        }

        // 处理红外控制/学习模式切换
        if (target.name === 'ir_mode') {
            const controlPanel = document.getElementById('ir-control-panel');
            const learnPanel = document.getElementById('ir-learn-panel');

            if (target.value === 'control') {
                controlPanel.classList.add('active');
                learnPanel.classList.remove('active');
            } else {
                learnPanel.classList.add('active');
                controlPanel.classList.remove('active');
            }
        }
    });
    
    // 事件委托，处理动态加载内容中的按钮点击
    pageContentContainer.addEventListener('click', (event) => {
        const target = event.target;

        // --- 处理 Tab 切换 ---
        if (target.classList.contains('ota-tab-btn')) {
            const tabName = target.dataset.tab;
            
            // 移除所有按钮的 active 类
            document.querySelectorAll('.ota-tab-btn').forEach(btn => btn.classList.remove('active'));
            // 移除所有内容的 active 类
            document.querySelectorAll('.ota-tab-content').forEach(content => content.classList.remove('active'));
            
            // 给被点击的按钮和对应内容添加 active 类
            target.classList.add('active');
            document.getElementById(`ota-tab-${tabName}`).classList.add('active');
            return; // 处理完Tab切换后，直接返回
        }

        const button = target.closest('button');
        if(!button) return;

        // --- 处理红外控制命令发送 ---
        if (button.dataset.command && !button.classList.contains('btn-learn')) {
            const command = {
                command: button.dataset.command,
                value: button.dataset.value,
                mode: button.dataset.mode || null // 如果没有mode,则为null
            };
            
            console.log('Sending IR command:', command);
            fetch(`/api/ir/send`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(command)
            })
            .then(res => res.json())
            .then(data => showHeaderMessage(data.message, true))
            .catch(err => showHeaderMessage(`错误: ${err.message}`, false));
            return; // 处理完后退出
        }

        // --- 处理红外学习命令 ---
        if (button.classList.contains('btn-learn')) {
            // 移除其他按钮的学习状态
            document.querySelectorAll('.btn-learn.learning').forEach(b => b.classList.remove('learning'));
            
            button.classList.add('learning'); // 给当前按钮添加学习中样式
            const instructions = document.getElementById('ir-learn-instructions');
            instructions.textContent = `学习中: ${button.textContent}... 请将遥控器对准设备并按下对应按键。`;
            
            const commandToLearn = {
                command: button.dataset.command,
                value: button.dataset.value,
                mode: button.dataset.mode || null
            };

            fetch(`/api/ir/learn`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(commandToLearn)
            })
            .then(res => {
                if (!res.ok) throw new Error('学习超时或失败');
                return res.json();
            })
            .then(data => {
                showHeaderMessage(data.message, true);
                instructions.textContent = `学习成功: ${button.textContent}！请选择下一个要学习的按键。`;
            })
            .catch(err => {
                showHeaderMessage(err.message, false);
                instructions.textContent = '学习失败，请重试。';
            })
            .finally(() => {
                button.classList.remove('learning'); // 移除学习中样式
            });
            return; // 处理完后退出
        }

        const buttonId = button.id;
        switch(buttonId) {
            case 'reboot-device-btn':
                if (confirm('您确定要重启设备吗?')) {
                    fetch(`/api/reboot`, { method: 'POST' })
                        .then(res => res.json())
                        .then(data => showHeaderMessage(data.message || '重启命令已发送', true))
                        .catch(err => showHeaderMessage(`错误: ${err.message}`, false));
                }
                break;

            case 'factory-reset-btn':
                // 二次确认，要求用户输入特定文字
                const confirmationText = 'RESET';
                const userInput = prompt(`这是一个危险操作！\n\n所有配置都将被清除。\n要继续，请输入 "${confirmationText}"`);
                
                if (userInput === confirmationText) {
                    showHeaderMessage('正在执行恢复出厂设置...', true);
                    fetch(`/api/factory-reset`, { method: 'POST' })
                        .then(res => res.json())
                        .then(data => showHeaderMessage(data.message || '设备正在恢复出厂设置', true))
                        .catch(err => showHeaderMessage(`错误: ${err.message}`, false));
                } else if(userInput !== null) { // 如果用户点击了 "OK" 但输入错误
                    showHeaderMessage('输入不正确，操作已取消', false);
                }
                break;

            case 'upload-firmware-btn':
                handleFirmwareUpload();
                break;
            
            case 'url-upgrade-btn':
                handleUrlUpgrade();
                break;

            case 'sync-time-btn':
                button.disabled = true;
                button.textContent = '校准中...';
                fetch(`/api/control/sync-time`, { method: 'POST' })
                    .then(res => res.json())
                    .then(data => {
                        showHeaderMessage(data.message, true);
                        // 之前是调用 initializeControlPage()，现在改为调用 initializeMaintenancePage()
                        initializeMaintenancePage(); 
                    })
                    .catch(err => showHeaderMessage(`错误: ${err.message}`, false))
                    .finally(() => {
                        button.disabled = false;
                        button.textContent = '立即校准';
                    });
                break;

            case 'ir-learn-btn':
                const irStatus = document.getElementById('ir-learn-status');
                button.disabled = true;
                button.textContent = '学习中...';
                irStatus.textContent = '请在3秒内将遥控器对准设备并按下按键...';

                fetch(`/api/control/ir-learn`, { method: 'POST' })
                    .then(res => res.json())
                    .then(data => {
                        showHeaderMessage(data.message, true);
                        irStatus.textContent = `学习成功！码值: ${data.code}`;
                    })
                    .catch(err => {
                        showHeaderMessage(`错误: ${err.message}`, false);
                        irStatus.textContent = '学习失败，请重试。';
                    })
                    .finally(() => {
                        button.disabled = false;
                        button.textContent = '开始学习';
                    });
                break;
        }
    });

    // --- 初始化 ---
    const initializeDashboard = () => {

        // 从 sessionStorage 获取并显示用户名
        const loggedInUsername = sessionStorage.getItem('username');
        if (loggedInUsername) {
            document.getElementById('username').textContent = loggedInUsername;
        }
        
        // --- 全局运行SSE ---
        // 如果你希望无论在哪个页面都能接收实时数据(例如更新页脚的某个状态)，
        // 可以在这里调用 startSseConnection()。
        startSseConnection();

        // 1. 加载默认页面 (设备状态)
        loadPage('status');

        // 2. 获取固件版本
        fetchFirmwareVersion();
        
        // 获取设备主机名
        // 假设ESP32在 /api/status 返回的数据中包含 hostname
        fetch(`/api/status`)
            .then(res => res.json())
            .then(data => {
                if (data.hostname) {
                    deviceHostnameSpan.textContent = data.hostname;
                }
            })
            .catch(console.error);
        
        // 初始化通知UI
        updateNotificationUI();
        
        // 模拟接收到一条通知
        setTimeout(() => {
            addNotification("系统已启动成功");
        }, 2000);

    };

    initializeDashboard();
});